/**
 * \file Cache.cc
 * \brief VM cache.
 * \author Corey Tabaka
 */

/*
   Copyright 2007 Corey Tabaka

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <ktypes.h>
#include <panic.h>
#include <vm/Cache.h>
#include <vm/AddressSpace.h>

DEF_NULL_REF(Cache);

Cache::Cache(RefStore _store, uint32 _size, uint32 _options) : self(this, true),
	cache(0), store(_store), size(_size), options(_options) {
}

Cache::Cache(RefCache _cache, uint32 _size, uint32 _options) : self(this, true),
	cache(_cache), store(0), size(_size), options(_options) {
}

Cache::~Cache(void) {
	while (!pages.isEmpty()) {
		Page *page = QList_removeHead(pages, Page, cacheNode);
		page->setState(PAGE_STATE_FREE);
	}
}

void Cache::insert(Region &region) {
	regions.append(&region.cacheNode);
}

void Cache::remove(Region &region) {
	region.cacheNode.remove();
}

void Cache::insert(Page &page) {
	pages.append(&page.cacheNode);
	page.cache = self;
	
	pageHash.put(page.offset, &page);
}

void Cache::remove(Page &page) {
	page.cacheNode.remove();
	page.cache = RefCache(0);
	
	pageHash.remove(page.offset);
}

Page *Cache::lookup(offset_t offset) {
	Page *page = 0;
	pageHash.get(offset, page);
	
	return page;
}
